/**
 * Copyright (c) 华南农业大学信息学院蔡超敏2015版权所有
 * 
 * 文件创建时间：2015年4月3日
 */
package org.scauinfo.fpos.action.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.scauinfo.fpos.action.BaseAction;
import org.scauinfo.fpos.model.UserModel;
import org.scauinfo.fpos.service.UserService;
import org.scauinfo.fpos.service.UserpermissionService;
import org.scauinfo.fpos.service.UserroleService;
import org.scauinfo.fpos.util.ExceptionUtil;
import org.scauinfo.fpos.util.Json;
import org.scauinfo.fpos.util.MD5;
import org.scauinfo.fpos.vo.User;
import org.scauinfo.fpos.vo.Userpermission;
import org.scauinfo.fpos.vo.Userrole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author 蔡超敏
 * 
 */
@Namespace("/")
@Scope("prototype")
@Controller
@Action(value = "user")
@RemoteProxy(name = "userAction")
public class UserAction extends BaseAction implements ModelDriven<User> {

	private static final long serialVersionUID = 3088843221530537631L;
	private static final Logger logger = Logger.getLogger(UserAction.class);
	@Autowired
	private UserService userService;

	@Autowired
	private UserroleService userroleService;
	@Autowired
	private UserpermissionService userpermissionService;

	public Userrole userrole = new Userrole();
	public User user = new User(userrole);
	
	@RemoteMethod
	public List<Map<String, Object>> getUsers() {
		try {
			List<User> users = userService.findAllUser();
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			System.out.println("!!!!!!!!!!!!");
			for (User user : users) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("account", user.getAccount());
				list.add(map);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	@RemoteMethod
	public String validateUser(String account,String password) {

		System.out.println("validateUser ----1"+account+password);
		User checkUser = userService.validateUser(account,
				MD5.getMD5Str(password.trim()));
		if (checkUser != null) {
			Map<String, Object> session = ActionContext.getContext()
					.getSession();
			session.put("user", checkUser);
			return null;
		} else {
			return "登陆失败";
		}
	}

	public void getTreeItem() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		User user = (User) session.get("user");

		Userrole userrole = user.getUserrole();
		System.out.println("getTreeItem - userrole"
				+ userrole.getRolePermissions());
		String temp = userrole.getRolePermissions();
		String[] arr = temp.split(",");

		System.out.println("getTreeItem - arr" + arr);
		String jsonTree = "[";
		for (int i = 0; i < arr.length; i++) {
			temp = arr[i];

			System.out.println("getTreeItem - 1" + temp);
			Userpermission userpermission = userpermissionService.get(Integer
					.parseInt(temp.trim()));
			System.out.println("getTreeItem - 2");
			jsonTree += "{\"text\": \"" + userpermission.getUpermissionName()
					+ "\",\"url\": \"" + userpermission.getUrules() + "\"}";
			if (i < arr.length - 1) {
				jsonTree += ",";
			}
			System.out.println("getTreeItem - 3");
		}
		jsonTree += "]";
		// String jsonTree = "[{\"text\": \"Node 1\",\"url\": \"user.jsp\"}]";

		System.out.println("getTreeItem - jsonTree" + jsonTree);
		try {
			ServletActionContext.getResponse().setContentType(
					"text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().write(jsonTree);
			ServletActionContext.getResponse().getWriter().flush();
		} catch (IOException e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
		}
	}

	/**
	 * 得到数据列表
	 */
	public void grid() {
		System.out.println("tags ----1");
		int total = userService.getTotal();
		System.out.println("tags ----total" + total + "page" + page + "rows"
				+ rows + ", sort" + sort + ", order" + order);
		List<User> list = userService.findAllUser(page, rows, sort, order);
		System.out.println("tags ----2" + list.size());

		List<UserModel> mList = new ArrayList<UserModel>();

		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			User User = (User) iterator.next();
			UserModel UserModel = new UserModel(User.getId(), User.getUserId(),
					User.getUsername(), User.getAccount(), User.getPassword(),
					User.getGender(), User.getTelephone());

			if (User.getUserrole() != null) {
				UserModel.setRoleId(User.getUserrole().getRoleId());
				UserModel.setRoleName(User.getUserrole().getRoleName());
				UserModel.setRolePermissions(User.getUserrole()
						.getRolePermissions());
			}
			mList.add(UserModel);
		}
		writeJson(total, mList);
		System.out.println("tags ----3");
	}

	/**
	 * 添加操作
	 */
	public void add() {
		Json result = new Json();

		System.out.println("tags ----User" + user.getUserId());
		try {
			user.setUserrole(userroleService.get(user.getUserrole().getId()));
			System.out.println("tags ----User" + user.getUserrole().getId());
			System.out
					.println("tags ----User" + user.getUserrole().getRoleId());

			// 使用MD5加密密码
			user.setPassword(MD5.getMD5Str(user.getPassword().trim()));

			userService.saveUser(user);
			result.setSuccess(true);
			result.setMsg("添加用户成功");
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("添加用户失败");
		}
		writeJson(result);
	}

	/**
	 * 修改操作
	 */
	public void edit() {
		Json result = new Json();
		try {
			System.out.println("edit ----product" + user.getId());
			System.out.println("edit ----User" + user.getUserrole().getId());
			user.setUserrole(userroleService.get(user.getUserrole().getId()));
			System.out.println("edit ----User" + user.getUserrole().getId());
			user.setPassword(MD5.getMD5Str(user.getPassword().trim()));
			userService.updateUser(user);
			result.setSuccess(true);
			result.setMsg("修改用户成功");
			result.setSuccess(true);
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("修改用户失败");
		}
		writeJson(result);
	}

	/**
	 * 删除操作
	 */
	public void remove() {
		Json result = new Json();
		try {
			System.out.println("tags ----=" + user.getId());
			userService.deleteUser(user.getId());
			result.setSuccess(true);
			result.setMsg("删除用户成功");
		} catch (Exception e) {
			logger.debug(ExceptionUtil.getExceptionMessage(e));
			result.setMsg("删除用户失败");
		}
		writeJson(result);
	}

	@Override
	public User getModel() {
		return user;
	}
}